<?php

namespace App\Http\Controllers\CallingCards\Wechat;

use App\Http\Controllers\BaseController;
use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Service\CallingCards\CardService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CallingCardController extends BaseController
{

    /**
     * 获取名片信息
     *
     * @return JsonResponse
     */
    public function detail(Request $request)
    {
        try {
            $user = auth('callingCardsWeChat')->user();
            $arr = explode('s', (string)$request->id);
            $id = $arr[0];
            $shopId = (int)($arr[1] ?? 0);
            //获取名片信息
            $feishuInfo = CardService::getCardInfoById($user, $id, $shopId);
        } catch (\Exception $exception) {
            return $this->fail($exception->getCode(), $exception->getMessage());
        }
        return $this->success(compact('feishuInfo'));
    }


    /**
     * 微信小程序用户更新信息
     * @param Request $request
     * @return JsonResponse
     */
    public function updateUser(Request $request): JsonResponse
    {
        $user = auth('callingCardsWeChat')->user();

        $data['nickName']  = (string)$request->get('nickName', '');    // 昵称
        $data['headImage'] = (string)$request->get('headImage', '');   // 头像

        return $this->success(CardService::updateWxUserInfo($user, $data));
    }


    /**
     * 微信小程序用户授权更新用户手机号
     * @param Request $request
     * @return JsonResponse
     */
    public function updateUserMobile(Request $request): JsonResponse
    {
        $user = auth('callingCardsWeChat')->user();

        $this->validate(
            $request, [
                'encryptedData' => 'required|string',
                'iv'            => 'required|string',
            ]
        );
        $encryptedData = (string)$request->get('encryptedData', '');    // 加密数据
        $iv            = (string)$request->get('iv', '');

        return $this->success(CardService::updateUserMobile($user, $encryptedData, $iv));
    }
}
